package com.whfc.emp.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.whfc.common.enums.FenceType;
import com.whfc.common.exception.BizException;
import com.whfc.common.geometry.GeometryUtil;
import com.whfc.common.geometry.Point;
import com.whfc.common.geometry.Polygon;
import com.whfc.common.result.PageData;
import com.whfc.common.result.ResultEnum;
import com.whfc.common.util.PageUtil;
import com.whfc.emp.dao.AppFenceEmpMapper;
import com.whfc.emp.dao.AppFenceMapper;
import com.whfc.emp.dto.AppFenceDTO;
import com.whfc.emp.dto.AppFenceEmpDTO;
import com.whfc.emp.entity.AppFence;
import com.whfc.emp.entity.AppFenceEmp;
import com.whfc.emp.param.AppFenceAddParam;
import com.whfc.emp.param.AppFenceEmpAddParam;
import com.whfc.emp.param.AppFenceEmpDelParam;
import com.whfc.emp.param.AppFenceListParam;
import com.whfc.emp.service.AppFenceService;
import com.whfc.entity.dto.Apply.rep.RegionRep;
import com.whfc.fuum.dto.SysWorkAreaDTO;
import com.whfc.fuum.service.SysDeptService;
import com.whfc.fvs.dto.FvsDeviceDTO;
import com.whfc.fvs.service.FvsDeviceService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @ClasssName AppFenceServiceImpl
 * @Description 智能安全帽-电子围栏
 * @Author hw
 * @Date 2020/12/24 15:50
 * @Version 1.0
 */
@DubboService(interfaceClass = AppFenceService.class, version = "1.0.0")
public class AppFenceServiceImpl implements AppFenceService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AppFenceMapper appFenceMapper;

    @Autowired
    private AppFenceEmpMapper appFenceEmpMapper;

    @DubboReference(interfaceClass = FvsDeviceService.class, version = "1.0.0")
    private FvsDeviceService fvsDeviceService;

    @DubboReference(interfaceClass = SysDeptService.class, version = "1.0.0")
    private SysDeptService sysDeptService;

    @Override
    public List<AppFenceDTO> list(AppFenceListParam request) {
        logger.info("人员管理-电子围栏列表,request:{}", request);
        List<AppFenceDTO> list = appFenceMapper.selectByParam(request);
        for (AppFenceDTO appFenceDTO : list) {
            //设置项目名称
            String deptName = sysDeptService.getDeptNameById(appFenceDTO.getDeptId());
            appFenceDTO.setDeptName(deptName);
            String fvsDeviceIds = appFenceDTO.getFvsDeviceIds();
            if (fvsDeviceIds != null && !fvsDeviceIds.trim().isEmpty()) {
                // 将逗号分隔的设备ID字符串转换为整数列表
                List<Integer> deviceIds = new ArrayList<>();
                String[] idArray = fvsDeviceIds.split(",");
                for (String idStr : idArray) {
                    try {
                        if (!idStr.trim().isEmpty()) {
                            deviceIds.add(Integer.parseInt(idStr.trim()));
                        }
                    } catch (NumberFormatException e) {
                        logger.warn("设备ID格式错误: {}", idStr);
                    }
                }
                // 获取设备信息列表
                if (!deviceIds.isEmpty()) {
                    List<FvsDeviceDTO> fvsDevices = fvsDeviceService.list(deviceIds);
                    if (fvsDevices == null || fvsDevices.isEmpty()) continue;
                    List<com.whfc.emp.dto.FvsDeviceDTO> deviceDTOS = new ArrayList<>();
                    for (FvsDeviceDTO fvsDeviceDTO: fvsDevices){
                        com.whfc.emp.dto.FvsDeviceDTO dto = new com.whfc.emp.dto.FvsDeviceDTO();
                        BeanUtils.copyProperties(fvsDeviceDTO, dto);
                        deviceDTOS.add(dto);
                    }
                    appFenceDTO.setFvsDevices(deviceDTOS);
                }
            }
            //转换空间几何对象
            this.translate(appFenceDTO);
        }
        return list;
    }

    @Override
    public Integer add(AppFenceAddParam request) {
        logger.info("人员管理-添加电子围栏,request:{}", request);
        Integer id = request.getId();
        Integer type = request.getType();
        String polygon = null;
        String center = null;
        //多边形
        if (FenceType.POLYGON.value().equals(type)) {
            List<Point> polygonPointList = request.getPolygonPointList();
            if (polygonPointList == null || polygonPointList.size() < 3) {
                throw new BizException(ResultEnum.FAILURE.getCode(), "多边形参数不正确!");
            }
            //首位相连
            polygonPointList.add(polygonPointList.get(0));
            polygon = GeometryUtil.encodePolygon(new Polygon(polygonPointList));
        }
        //圆形
        else if (FenceType.CIRCLE.value().equals(type)) {
            Point centerPoint = request.getCenterPoint();
            Double radius = request.getRadius();
            if (centerPoint == null || radius == null) {
                throw new BizException(ResultEnum.FAILURE.getCode(), "圆形参数不正确!");
            }
            center = GeometryUtil.encodePoint(centerPoint);
        }
        AppFence appFence = new AppFence();
        appFence.setId(id);
        appFence.setName(request.getName());
        appFence.setDeptId(request.getDeptId());
        appFence.setType(type);
        appFence.setPolygon(polygon);
        appFence.setCenter(center);
        appFence.setRadius(request.getRadius());
        appFence.setFvsDeviceIds(request.getFvsDeviceIdsString());
        if (id == null) {
            //新增
            appFenceMapper.insertSelectiveByParam(appFence);
            id = appFence.getId();
        } else {
            //编辑
            appFenceMapper.updateSelectiveByParam(appFence);
        }
        return id;
    }

    @Override
    public void del(Integer id) {
        logger.info("人员管理-删除电子围栏,id:{}", id);
        List<AppFenceEmpDTO> list = appFenceEmpMapper.selectByFenceId(id, null, null, null);
        if (!list.isEmpty()) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "电子围栏下有人员无法删除");
        }
        appFenceMapper.deleteLogicById(id);
    }

    @Override
    public PageData<AppFenceEmpDTO> empList(Integer fenceId, Integer pageNum, Integer pageSize, Integer groupId, Integer workTypeId, String keyword) {
        logger.info("电子围栏考勤人员列表,fenceId:{},pageNum:{},pageSize:{},groupId:{},workTypeId:{},keyword:{}",
                fenceId, pageNum, pageSize, groupId, workTypeId, keyword);
        PageHelper.startPage(pageNum, pageSize);
        List<AppFenceEmpDTO> list = appFenceEmpMapper.selectByFenceId(fenceId, groupId, workTypeId, keyword);
        PageHelper.clearPage();
        return PageUtil.pageData(PageInfo.of(list));
    }

    @Override
    public void addEmp(AppFenceEmpAddParam request) {
        logger.info("电子围栏添加人员,request:{}", request);
        List<Integer> empList = request.getEmpList();
        Integer fenceId = request.getFenceId();
        List<AppFenceEmp> fenceEmpList = new ArrayList<>();
        for (Integer empId : empList) {
            AppFenceEmp appFenceEmp = new AppFenceEmp();
            appFenceEmp.setEmpId(empId);
            appFenceEmp.setFenceId(fenceId);
            fenceEmpList.add(appFenceEmp);
        }
        appFenceEmpMapper.insertOrUpdate(fenceEmpList);
    }

    @Override
    public void delEmp(AppFenceEmpDelParam request) {
        logger.info("删除考勤人员,request:{}", request);
        appFenceEmpMapper.deleteLogic(request.getFenceId(), request.getEmpId());
    }

    @Override
    public List<AppFenceDTO> listByEmpId(Integer empId) {
        logger.info("根据人员id查询所在的电子围栏列表,empId:{}", empId);
        List<AppFenceDTO> list = appFenceEmpMapper.selectByEmpId(empId);
        for (AppFenceDTO appFenceDTO : list) {
            this.translate(appFenceDTO);
        }
        return list;
    }

    @Override
    public PageData<AppFenceEmpDTO> unGrantList(Integer deptId, Integer fenceId, Integer pageNum, Integer pageSize, Integer groupId, String keyword) {
        logger.info("电子围栏考勤未授权人员列表,deptId:{},fenceId:{},pageNum:{},pageSize:{},groupId:{},keyword:{}"
                , deptId, fenceId, pageNum, pageSize, groupId, keyword);
        PageHelper.startPage(pageNum, pageSize);
        List<AppFenceEmpDTO> list = appFenceEmpMapper.selectUnGrantEmp(deptId, fenceId, groupId, keyword);
        return PageUtil.pageData(PageInfo.of(list));
    }

    @Override
    public List<AppFenceDTO> listByMsAppFence(Integer id) {
        return appFenceEmpMapper.listByMsAppFence(id);
    }

    @Override
    public AppFence listByMsAppFenceName(Integer id) {

        return appFenceMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<RegionRep> getWorkArea(Integer deptId) {
        return appFenceMapper.getWorkArea(deptId);
    }

    @Override
    public List<AppFenceDTO> areaList(Integer deptId) {
        return appFenceMapper.areaList(deptId);
    }

    @Override
    public List<AppFenceDTO> listByFvsDeviceId(Integer fvsDeviceId) throws BizException {
        return appFenceMapper.listByFvsDeviceId(fvsDeviceId);
    }

    /**
     * 转换空间几何对象
     *
     * @param appFenceDTO
     */
    private void translate(AppFenceDTO appFenceDTO) {
        if (FenceType.POLYGON.value().equals(appFenceDTO.getType())) {
            Polygon polygon = GeometryUtil.decodePolygon(appFenceDTO.getPolygon());
            appFenceDTO.setPolygonPointList(polygon.getPointList());
        }
        //圆形
        else if (FenceType.CIRCLE.value().equals(appFenceDTO.getType())) {
            Point point = GeometryUtil.decodePoint(appFenceDTO.getCenter());
            appFenceDTO.setCenterPoint(point);
        }
    }
}